package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author zjs
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo selectCheckInById(Long id) {
//查询入住表 , 获取老人ID
        //根据入住ID id 查询 check_in 表，获取入住记录 checkIn。
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //从入住记录中提取 elderId（老人ID），用于后续查询老人信息
        Long elderId = checkIn.getElderId();

//查询老人信息 → CheckInElderVo
        //根据 elderId 查询老人信息 elder。
        Elder elder = elderMapper.selectById(elderId);
        //使用 IdcardUtil 计算年龄（基于身份证号）。
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (ObjectUtils.isNotEmpty(elder)) {
            int age = IdcardUtil.getAgeByIdCard(elder.getIdCardNo());
            checkInElderVo.setAge(age);
            //使用 BeanUtils.copyProperties 将 Elder 对象的属性拷贝到 CheckInElderVo。
            BeanUtils.copyProperties(elder, checkInElderVo);
        }


// 查询老人家属信息 → List<ElderFamilyVo>
        //查获取老人家属信息
        String remark = checkIn.getRemark();
        //JSON转对象
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);


//查询入住配置信息 → CheckInConfigVo
        //从 check_in 表获取 startDate、endDate、bedNumber。
        LocalDateTime startDate = checkIn.getStartDate();
        LocalDateTime endDate = checkIn.getEndDate();
        String bedNumber = checkIn.getBedNumber();

        //根据 checkInId 查询 check_in_config 表，获取护理等级、费用等信息。
        Long checkInId = checkIn.getId();
        // 查询入住配置表
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId, checkInId);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);

        // 封装数据
        //使用 BeanUtil.copyProperties 拷贝属性，并补充入住日期、床位号。
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(bedNumber);
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);

        //查询合同

        LambdaQueryWrapper<Contract> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(lambdaQueryWrapper);


        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
//        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
//        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
//        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
//        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();


        //1.检验老人是否已入住 , 如果已经入住直接抛出异常 BaseException
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }

        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人
        elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);

        //4.新增签约办理 , 合同信息 : HT
        insertContract(elder, dto);

        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);

        //6.新增入住配置
        insertCheckInConfig(checkIn, dto);


    }


    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        Elder e = new Elder();
        BeanUtils.copyProperties(checkInElderDto, e);
        e.setBedId(bed.getId());
        e.setBedNumber(bed.getBedNumber());
        e.setStatus(1);

        //新增/修改
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        elderLambdaQueryWrapper.eq(Elder::getStatus, 0);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        //elderMapper.insertElder(elder);
        if (ObjectUtils.isEmpty(elder)) {
            elderMapper.insert(e);
        } else {
            e.setId(elder.getId());
            elderMapper.updateById(e);
        }
        return e;
    }

    private void insertContract(Elder elder, CheckInApplyDto dto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());

        //从入住配置中获取开启和结束的时间(入住的开始和结束时间)
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();

        contract.setStartDate(startDate);
        contract.setEndDate(endDate);

        //判断合同状态
        // startDate : 2025-07-25 00:00:00
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;

        //保存
        contractMapper.insert(contract);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(0);

        //保存老人家属信息
        //老人家属信息只用于数据展示 , 转换为JSON字符串 , 并存入CheckIn表中的remark字段中
        //对象转JSON
        String jsonString = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));

        //JSON转对象
        List<ElderFamilyDto> elderFamilyDtos = JSON.parseArray(jsonString, ElderFamilyDto.class);

        checkInMapper.insert(checkIn);

        return checkIn;
    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }
}













